package com.cozy.android.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.cozy.android.sdk.CozyBusiness;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class CozyUnityBridge implements CozyUnityIAP {

    private static CozyUnityBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private static Handler handler = new Handler(Looper.getMainLooper());
    private Method mCallback;

    public static CozyUnityBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new CozyUnityBridge();
        }
        return callbackApi;
    }

    private CozyUnityBridge(){
        try {
            Class clzBridge = Class.forName("com.unity3d.player.UnityPlayer", false, CozyBusiness.context.getClassLoader());
            mCallback = clzBridge.getDeclaredMethod("UnitySendMessage", String.class, String.class, String.class);
            mCallback.setAccessible(true);
        } catch (Exception e) {
        }
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if(mCallback != null && handler != null){
            try{
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            JSONObject jCallback = new JSONObject();
                            jCallback.put("action", action);
                            if(!TextUtils.isEmpty(jsonData)){
                                Object obj = null;
                                if(jsonData.startsWith("{")){
                                    obj = new JSONObject(jsonData);
                                }else if (jsonData.startsWith("[")){
                                    obj = new JSONArray(jsonData);
                                }
                                if(obj != null) {
                                    jCallback.put("jsonData", obj);
                                }
                            }
                            mCallback.invoke(null, "CMSdkCallback", "callback", jCallback.toString());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
